package com.example.getwifiip

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.net.wifi.WifiManager
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.example.getwifiip.utils.HttpConnectionUtil
import com.example.getwifiip.utils.RuntimeRationale
import com.yzq.zxinglibrary.android.CaptureActivity
import com.yzq.zxinglibrary.common.Constant
import java.util.*
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.PermissionDef
import com.yanzhenjie.permission.runtime.Permission


class MainActivity : AppCompatActivity() {

    lateinit var mContext: Context
    lateinit var editServeIp: EditText
    lateinit var confirmBtn: Button
    lateinit var showIp: TextView
    lateinit var result: TextView
    lateinit var qrcodeBtn: Button
    lateinit var ipAddress: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_wifi)
        mContext = this

        editServeIp = this.findViewById(R.id.edit_serve_ip)
        confirmBtn = this.findViewById(R.id.confirm_btn)
        showIp = this.findViewById(R.id.show_ip)
        result = this.findViewById(R.id.tv_result)

        qrcodeBtn = this.findViewById(R.id.create_qrcode_btn)

        // 这种方式只能获取wifi ip
        val wm = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val ipAddressInt = wm.connectionInfo.ipAddress
        ipAddress = String.format(
            Locale.getDefault(),
            "%d.%d.%d.%d",
            ipAddressInt and 0xff,
            ipAddressInt shr 8 and 0xff,
            ipAddressInt shr 16 and 0xff,
            ipAddressInt shr 24 and 0xff
        )
        showIp.text = ipAddress

        confirmBtn.setOnClickListener {
            val serial = android.os.Build.SERIAL
            if (!editServeIp.text.toString().contains("&serial=")) {
                editServeIp.setText(editServeIp.text.toString() + "&serial=" + serial)
            }
            val res =
                HttpConnectionUtil().getRequest(editServeIp.text.toString())
            result.text = res
            Toast.makeText(this, res, Toast.LENGTH_SHORT).show()
        }

        qrcodeBtn.setOnClickListener {
            requestPermission(Permission.CAMERA)
            requestPermission(Permission.READ_EXTERNAL_STORAGE)
            val intent = Intent(this, CaptureActivity::class.java)
            startActivityForResult(intent, REQUEST_CODE_SCAN)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                val bundle = data?.extras
                val scanResult = bundle?.getString(Constant.CODED_CONTENT)
                Toast.makeText(this, scanResult, Toast.LENGTH_SHORT).show()
                if (!editServeIp.text.toString().contains("&serial=")) {
                    val serial = android.os.Build.SERIAL
                    editServeIp.setText(scanResult.toString() + "?client=" + ipAddress + "&serial=" + serial)
                }
            }
        }
    }

    companion object {
        const val REQUEST_CODE_SCAN = 9999
    }

    /**
     * Request permissions.
     */
    private fun requestPermission(@PermissionDef vararg permissions: String) {
        AndPermission.with(this)
            .runtime()
            .permission(*permissions)
            .rationale(RuntimeRationale())
            .onGranted { Toast.makeText(mContext, "succ", Toast.LENGTH_SHORT).show() }
            .onDenied { permissions ->
                Toast.makeText(mContext, "fail", Toast.LENGTH_SHORT).show()
                if (AndPermission.hasAlwaysDeniedPermission(mContext, permissions)) {
                    Toast.makeText(mContext, "去打开相机权限", Toast.LENGTH_SHORT).show()
                }
            }
            .start()
    }
}
